package com.jhh.pay.driver.service.impl.v1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.jhh.pay.driver.pojo.PayRequest;
import com.jhh.pay.driver.pojo.PayResponse;
import com.jhh.pay.driver.service.DiscoveryService;
import com.jhh.pay.driver.service.TradeService;

@Component
public class TradeServiceImpl implements TradeService{
	
	private static final String SERVICE_NAME = "pay-center";
	
	private static final String PAY_PATH = "/jhhpay/trade/1.0/pay";
	private static final String DEDUCT_PATH = "/jhhpay/trade/1.0/deduct";
	private static final String STATE_PATH = "/jhhpay/query/1.0/state";
	private static final String ORDER_PATH = "/jhhpay/query/1.0/order";
	private static final String SEARCH_PATH = "/jhhpay/query/1.0/search";
	
	@Autowired
	private DiscoveryService discoveryService;
	
	private String getBaseUrl()  {
		InetSocketAddress sa = discoveryService.getServiceAddress(SERVICE_NAME);
		if(sa == null) {
			throw new RemoteAccessException("无法获得服务地址");
		}
		return "http://"+sa.getHostName()+":"+sa.getPort();
	}

	@Override
	public PayResponse pay(PayRequest req) {
		return doRequest(req, PAY_PATH);
	}

	@Override
	public PayResponse deduct(PayRequest req) {
		return doRequest(req, DEDUCT_PATH);
	}

	@Override
	public PayResponse state(PayRequest req) {
		return doRequest(req, STATE_PATH);
	}

	@Override
	public PayResponse order(PayRequest req) {
		return doRequest(req, ORDER_PATH);
	}

	@Override
	public PayResponse search(PayRequest req) {
		return doRequest(req, SEARCH_PATH);
	}
	
	private PayResponse doRequest(PayRequest req, String path) {
		try {
			URL url = new URL(getBaseUrl()+path);
			HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
			urlCon.setDoInput(true);
			urlCon.setDoOutput(true);
			urlCon.setRequestMethod("POST");
			urlCon.setRequestProperty("Content-Length", String.valueOf(req.toString().getBytes().length));
			urlCon.setUseCaches(false);
			urlCon.getOutputStream().write(req.toString().getBytes());
			urlCon.getOutputStream().flush();
			urlCon.getOutputStream().close();
			InputStream inputStream = urlCon.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = in.readLine()) != null) {
				builder.append(line);
			}
			return JSON.parseObject(builder.toString(), PayResponse.class);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return PayResponse.localFailed();
	}
	
}
